package com.software.car.controller;

import com.software.car.api.FileSavaService;
import com.software.car.common.enums.ResultEnum;
import com.software.car.common.utils.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author 魔法はまだ解けない
 * @Date 2021/2/9
 */
@RestController
public class ImgController {

    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    FileSavaService fileSavaService;

    /**
     *
     * 上传文件
     *
     * @param multipartFile
     * @return      文件名称
     */
    @PostMapping("/fileUpload")
    @PreAuthorize("hasAnyRole('ROLE_SUPER_ADMINISTER','ROLE_ADMINISTER')")
    public CommonResult fileUpload(@RequestParam(value = "file") MultipartFile multipartFile) throws IOException {
        logger.info("执行ImgController——路径：/fileUpload");
        logger.info("执行ImgController：fileUpload()方法");
        if (multipartFile.isEmpty()) {
            return CommonResult.fail(ResultEnum.FILE_UPLOAD);
        }
        String name = fileSavaService.uploadFile(multipartFile);
        return CommonResult.success(name);
    }

    /**
     * 下载文件
     * @param fileName  文件名
     * @param type      文件下载类型
     * @param response
     * @return  操作成功
     * @throws IOException
     */
    @GetMapping("/public")
    public void getFile(@RequestParam(name = "fileName") String fileName,
                                @RequestParam(name = "type",required = false)Integer type,
                                HttpServletResponse response) throws IOException {
        logger.info("执行ImgController——路径：/public");
        logger.info("执行ImgController：getFile()方法");
        /**
         * 设置文件名
         */
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
        if (type != null) {

            /**
             * 设置保存方式为下载
             */
            response.setContentType("application/force-download");
        }
        fileSavaService.getFile(fileName,response);
    }
}
